package extension

import android.app.Activity
import android.os.Bundle
import androidx.fragment.app.Fragment
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty


/**
 * 用法示例
 * // age int类型，默认值20，key未指定，取字段名age
 * private val age by argument(20)
 * // 声明key，声明默认值
 * private val id by argument(key = "ID", defaultValue = 10)
 * // 无默认值
 * private val id2 by argument<Int?>(null)
 */
fun <T> Activity.argument(
    defaultValue: T,
    key: String? = null
): ReadOnlyProperty<Activity, T> =
    ActivityArgumentProperty(key, defaultValue)

private class ActivityArgumentProperty<T>(
    private val key: String?,
    private val defaultValue: T
) :
    ReadOnlyProperty<Activity, T> {
    override fun getValue(thisRef: Activity, property: KProperty<*>): T {
        return thisRef.intent?.extras?.getValue<T>(key ?: property.name) ?: defaultValue
    }

}

fun <T> Fragment.argument(
    defaultValue: T,
    key: String? = null
): ReadOnlyProperty<Fragment, T> =
    FragmentArgumentProperty(key, defaultValue)

private class FragmentArgumentProperty<T>(
    private val key: String?,
    private val defaultValue: T
) :
    ReadOnlyProperty<Fragment, T> {
    override fun getValue(thisRef: Fragment, property: KProperty<*>): T {
        return thisRef.arguments?.getValue<T>(key ?: property.name) ?: defaultValue
    }

}

@Suppress("UNCHECKED_CAST")
fun <T> Bundle.getValue(key: String): T? {
    return this.get(key) as? T
}
